package pt.inescid.components.overlaymanager;
import rice.p2p.commonapi.Id;

/**
 * 
 * Node's Reputation
 * 
 * @author Filipe Paredes
 * @author Sergio Esteves
 */
public class NodeReputation {

  /**
   * Node Id
   */
  private Id id;
  /**
   * Metrics of this node: % of fails, num of retries, num of gridlets that came
   * back to origin, existence of an alternative and num of times that this node
   * was chosen
   */
  private double fails,  retries,  backToOrigin,  alternative,  choosen;
  
  private int NUM_RETRIES;

  /**
   * Constructor.
   */
  public NodeReputation(Id id, int NUM_RETRIES) {
    this.id = id;
    this.fails = 0;
    this.retries = 0;
    this.backToOrigin = 0;
    this.alternative = 100;
    this.choosen = 0;
    this.NUM_RETRIES = NUM_RETRIES;
  }

  /*** Get Methods ***/
  public Id getId() {
    return id;
  }

  public double getFails() {
    if(choosen==0) return 0;
    return ((fails * 100) / choosen);
  }

  public double getRetries() {
    if(choosen==0) return 0;
    return ((retries * 100) / (choosen * NUM_RETRIES));
  }

  public double getBackToOrigin() {
    if(choosen==0) return 0;
    return ((backToOrigin * 100) / choosen);
  }

  public double getAlternative() {
    return alternative;
  }

  public double getChoosen() {
    return choosen;
  }

  // Weighted sum of the parts, favors number of fails
  public double getRate() {
    if (choosen == 0) {
      return 100;
    }
      
    return (getFails() * 0.7) + (getBackToOrigin() * 0.25) + (getRetries() * 0.05);
  }

  /*** Update Methods ***/
  public void updateFails(double fails) {
    this.fails += fails;
  }

  public void updateRetries(double retries) {
    this.retries += retries;
  }

  public void updateBackToOrigin(double backToOrigin) {
    this.backToOrigin += backToOrigin;
  }

  public void updateAlternative(double alternative) {
    this.alternative = alternative;
  }

  public void updateChoosen(double choosen) {
    this.choosen += choosen;
  }

  public String toString() {
    return "Node " + id + " [" + getFails() + ", " + getRetries() + ", " +
            getBackToOrigin() + ", " + getAlternative() + ", " + getChoosen() + "]";
  }
}
